package com.zhaoye.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zhaoye.entities.CommonResult;
import com.zhaoye.entities.Payment;
import com.zhaoye.handler.CustomerBlockHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author feng
 * @Date 2021/11/20 21:16
 * 实现sentinel的降级规则处理
 */
@RestController
@Slf4j
public class RateLimitcontroller {

    //QPS流控测试
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handlerException")
    public CommonResult byResource() {
        return new CommonResult(200, "按资源名称限流监控，", new Payment(2020L, "serial001"));
    }

    public CommonResult handlerException(BlockException exception) {
        return new CommonResult(404, exception.getClass().getCanonicalName() + "\t 服务不可用");
    }

    //没有兜底的方法，系统默认使用自带的
    @GetMapping(value = "/rateLimit/byurl")
    @SentinelResource(value = "byurl")
    public CommonResult byurl() {
        return new CommonResult(200, "按url进行测试ok", new Payment(2020L, "serial002"));
    }

    //自定义异常处理机制
    @GetMapping(value = "/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",blockHandlerClass = CustomerBlockHandler.class,
                      blockHandler = "handlerException2")
    public CommonResult customerBlockHandler() {
        return new CommonResult(200, "按客戶自定义", new Payment(2020L, "serial003"));
    }
}
